package com.csust.automaticteach.utils.logging.userinfo;

import com.csust.automaticteach.model.entity.User;
import com.csust.opration.logger.core.model.OperationUser;
import com.csust.opration.logger.core.userinfo.LogUserInfoAdapter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import static com.csust.automaticteach.constant.UserConstant.USER_LOGIN_STATE;

/**
 * ClassName LoginLogUserImpl
 *
 * @Description 获取当前登录用户信息
 * @Author 钰玟
 * @Date 2025/8/11 下午4:36
 * Version 1.0
 **/

public class LoginLogUserImpl implements LogUserInfoAdapter {
    @Override
    public OperationUser getCurrentUser() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        //1. 从Session 中获取存入的User对象
        Object userObj = session.getAttribute(USER_LOGIN_STATE);
        //强转
        User currentUser = (User) userObj;
        OperationUser operationUser = new OperationUser();
        operationUser.setUserId(String.valueOf(currentUser.getId()));
        operationUser.setUsername(currentUser.getUserName());
        operationUser.setRole(currentUser.getUserRole());
        operationUser.setIpAddress(request.getRemoteAddr());
        operationUser.setPath(request.getRequestURI());
        return operationUser;
    }
}
